﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using uMES.LeanManufacturing.ParameterDTO;
using uMES.LeanManufacturing.ReportBusiness;
using uMES.LeanManufacturing.DBUtility;
using Infragistics.WebUI.UltraWebGrid;

public partial class Custom_BwProcessEditor_BwTempProcessWorkHoursEditor : BaseForm
{
    uMESWorkflowEditorBusiness workflowBal = new uMESWorkflowEditorBusiness();
    uMESContainerBusiness containerBal = new uMESContainerBusiness();
    uMESCommonBusiness commonBal = new uMESCommonBusiness();
    string businessName = "基础数据", parentName = "workflow";
    protected void Page_Load(object sender, EventArgs e)
    {
        WebPanel = WebAsyncRefreshPanel1;
        DisplayMessage("", true);
        if (IsPostBack == false)
        {

        }
     }

    #region 事件
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        try
        {
            ResetData(true, true);
            SearchData();
        }
        catch (Exception ex)
        {
            DisplayMessage(ex.Message, false);
        }
    }
        
    protected void btnReSet_Click(object sender, EventArgs e)
    {
        try
        {
            ResetData(true, true);
        }
        catch (Exception ex)
        {
            DisplayMessage(ex.Message, false);
        }
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        try
        {
            var re = SaveData();
            if (re.IsSuccess)
            {
                wgWorkflow_ActiveRowChange(null,null);
                DisplayMessage(re.Message, re.IsSuccess);                             

            }
            else {
                DisplayMessage(re.Message,re.IsSuccess);
            }
        }
        catch (Exception ex)
        {
            DisplayMessage(ex.Message, false);
        }
    }

    protected void wgWorkflow_ActiveRowChange(object sender, Infragistics.WebUI.UltraWebGrid.RowEventArgs e)
    {
        try
        {
            ResetData(false,true); ActiveWorkflowRow();
        }
        catch (Exception ex)
        {
            DisplayMessage(ex.Message, false);
        }
    }

    protected void wgSpec_InitializeRow(object sender, Infragistics.WebUI.UltraWebGrid.RowEventArgs e)
    {
        try
        {
            if (string.IsNullOrWhiteSpace(e.Row.Cells.FromKey("DetailSetupWorktime").Text))
            {
                e.Row.Cells.FromKey("EditSetupWorkTime").Value = e.Row.Cells.FromKey("SetupWorktime").Text;
            }
            else {
                e.Row.Cells.FromKey("EditSetupWorkTime").Value = e.Row.Cells.FromKey("DetailSetupWorktime").Text;
            }

            if (string.IsNullOrWhiteSpace(e.Row.Cells.FromKey("DetailUnitWorktime").Text))
            {
                e.Row.Cells.FromKey("EditUnitWorkTime").Value = e.Row.Cells.FromKey("UnitWorktime").Text;
            }
            else
            {
                e.Row.Cells.FromKey("EditUnitWorkTime").Value = e.Row.Cells.FromKey("DetailUnitWorktime").Text;
            }

            if (e.Row.Cells.FromKey("IsModifyWorkHours").Text=="1")
            {
                e.Row.Cells.FromKey("IsModifyWorkHours").Value = "是";
            }
            else
            {
                e.Row.Cells.FromKey("IsModifyWorkHours").Value = "";
            }

        }
        catch (Exception ex)
        {
            DisplayMessage(ex.Message, false);
        }
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        try
        {
            ClearMessage();

            UltraGridRow uldr = wgWorkflow.DisplayLayout.ActiveRow;
            if (uldr == null)
            {
                DisplayMessage("请选择记录", false);
                //Infragistics.WebUI.Shared.CallBackManager.AddScriptBlock(Page, WebAsyncRefreshPanel1, "<script>alert('请选择批次记录')</script>");
                return;
            }

            DataTable poupDt = new DataTable();
            poupDt.Columns.Add("ProductID");
            poupDt.Columns.Add("WorkflowID");
            DataRow newRow = poupDt.NewRow();
            DataTable productDt = containerBal.GetTableInfo("productbase","productname", uldr.Cells.FromKey("ProductName").Text);
            newRow["ProductID"] = productDt.Rows[0]["revofrcdid"].ToString();
            newRow["WorkflowID"] = uldr.Cells.FromKey("WorkflowID").Text;
            poupDt.Rows.Add(newRow);
            Session.Add("ProcessDocument", poupDt);

            //string strScript = string.Empty;
            //strScript = "<script>window.showModalDialog('../bwCommonPage/uMESDocumentViewPopupForm.aspx', '', 'dialogWidth: 700px; dialogHeight: 600px; status = no; center: Yes; resizable: NO; ')</script>";
            //Infragistics.WebUI.Shared.CallBackManager.AddScriptBlock(Page, WebAsyncRefreshPanel1, strScript);

            var page = "../bwCommonPage/uMESDocumentViewPopupForm.aspx";
            var script = String.Format("<script>OpenPopupWindow(false,'{0}','dialogWidth={1}px;dialogHeight={2}px;status=0');</script>", page, 700, 600);
            Infragistics.WebUI.Shared.CallBackManager.AddScriptBlock(Page, WebAsyncRefreshPanel1, script);
        }
        catch (Exception ex)
        {
            DisplayMessage(ex.Message, false);
        }
    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        try
        {
            var re = SubmitData();

            DisplayMessage(re.Message, re.IsSuccess);
        }
        catch (Exception ex)
        {
            DisplayMessage(ex.Message, false);
        }
    }
    #endregion


    #region 方法
    void SearchData() {
        Dictionary<string, string> para = new Dictionary<string, string>();

        if (!string.IsNullOrWhiteSpace(txtProduct.Text)) {
            para.Add("ProductName",txtProduct.Text);
        }

        if (!string.IsNullOrWhiteSpace(txtWorkflow.Text))
        {
            para.Add("WorkflowName", txtProduct.Text);
        }

        var re = workflowBal.GetCanWorkHoursWorkflowInfo(para);

        wgWorkflow.DataSource = re.DBTable;
        wgWorkflow.DataBind();
    }

    void ResetData(bool isWorkflow,bool isSpec) {
        if (isWorkflow)
            wgWorkflow.Rows.Clear();
        if (isSpec)
            wgSpec.Rows.Clear();
    }

    void ActiveWorkflowRow() {
        var activeRow = wgWorkflow.DisplayLayout.ActiveRow;
        var workflowId = activeRow.Cells.FromKey("WorkflowID").Text;
        DataTable dt = workflowBal.GetWorkflowStepInfoByWorkflowId(workflowId);
        wgSpec.DataSource = dt;
        wgSpec.DataBind();
    }
    /// <summary>
    /// 保存工时
    /// </summary>
    /// <returns></returns>
    ResultModel SaveData() {
        ResultModel re = new ResultModel(false,"");

        ////验证是否是以,号分割的数字
        //Regex regex = new Regex("^\\d+[,]\\d+$");        

        //re.Message= regex.IsMatch("112,0").ToString();

        //return re;

        DataTable selectDt = uMESCommonFunction.GetGridChooseInfo2(wgSpec,null,"ckSelect");

        if(selectDt.Rows.Count==0)
            return new ResultModel(false, "请选择记录");
        //数据验证
        foreach (DataRow dr in selectDt.Rows)
        {
            if (string.IsNullOrWhiteSpace(dr["EditUnitWorkTime"].ToString()) || string.IsNullOrWhiteSpace(dr["EditSetupWorkTime"].ToString())) {
                return new ResultModel(false, "请录入工时");
            }
            //验证格式是否正确
            if (dr["OperationName"].ToString().Contains('、'))
            {
                //验证是否是以,号分割的数字
                Regex regex = new Regex("^\\d+[,]\\d+$");
                if (regex.IsMatch(dr["EditUnitWorkTime"].ToString())==false|| regex.IsMatch(dr["EditSetupWorkTime"].ToString()) == false) {
                    return new ResultModel(false, dr["OperationName"].ToString() + "工时数据格式录入错误");
                }

                //if (!dr["EditUnitWorkTime"].ToString().Contains(",") || !dr["EditSetupWorkTime"].ToString().Contains(","))
                //{
                //    return new ResultModel(false, dr["OperationName"].ToString() + "工时数据格式录入错误");
                //}
               
            }
            else {
                int temp = 0;
                if (int.TryParse(dr["EditUnitWorkTime"].ToString(), out temp) == false) {
                    return new ResultModel(false, dr["OperationName"].ToString() + "工时数据格式录入错误");
                }
                if (int.TryParse(dr["EditSetupWorkTime"].ToString(), out temp) == false)
                {
                    return new ResultModel(false, dr["OperationName"].ToString() + "工时数据格式录入错误");
                }
            }
        }

        //数据修改
        foreach (DataRow dr in selectDt.Rows)
        {
            string tempUnitWorkTime = dr["UnitWorkTime"].ToString(), tempSetupWorkTime = dr["SetupWorkTime"].ToString();

            var editUnitWorkTime = dr["EditUnitWorkTime"].ToString(); var editSetupWorkTime = dr["EditSetupWorkTime"].ToString();
            if (editUnitWorkTime.Contains(","))
            {
                dr["detailunitworktime"] = dr["EditUnitWorkTime"];
            }
            else {
                dr["UnitWorkTime"] = dr["EditUnitWorkTime"];
            }

            if (editSetupWorkTime.Contains(","))
            {
                dr["detailsetupworktime"] = dr["EditSetupWorkTime"];
            }
            else {
                dr["SetupWorkTime"] = dr["EditSetupWorkTime"];
            }

            dr["IsModifyWorkHours"] = "1";

          re=  workflowBal.SaveSpec(UserInfo["ApiEmployeeName"], UserInfo["ApiPassword"], dr);
            if (re.IsSuccess == false)
                return re;

            WriteWorkHoursRecord(dr, tempUnitWorkTime, tempSetupWorkTime);
        }
        //刷新工序信息
        var activeRow = wgWorkflow.DisplayLayout.ActiveRow;
        var worklfowId = activeRow.Cells.FromKey("WorkflowID").Text;
        DataTable dt = workflowBal.GetWorkflowStepInfoByWorkflowId(worklfowId);
        wgSpec.DataSource = dt;
        wgSpec.DataBind();
        //激活工艺,全部都有工时情况下
        //if (dt.Select("SynergicName='否' and (unitworktime is null or setupworktime is null)").Length == 0)
        //{
        //    OracleHelper.ExecuteDataByEntity(new ExcuteEntity("workflow", ExcuteType.update)
        //    {
        //        ExcuteFileds = new List<FieldEntity> {new FieldEntity("status","1",FieldType.Numer)
        //    },
        //        WhereFileds = new List<FieldEntity> { new FieldEntity("workflowid", worklfowId, FieldType.Str) }
        //    });
        //    re.Message = "保存成功";
        //}
        //else {
        //    re.Message = "保存成功,有工序未维护完工时";
        //}    

        re.Message = "保存成功";

        WriteLogToAudit(worklfowId,1,"临时工艺:"+activeRow.Cells.FromKey("WorkflowName").Text+":"+activeRow.Cells.FromKey("WorkflowRev").Text +"工时维护");

        re.IsSuccess = true;
            return re;       
    }
    /// <summary>
    /// 提交工艺
    /// </summary>
    /// <returns></returns>
    ResultModel SubmitData()
    {
        ResultModel re = new ResultModel(false,"");
        //刷新工序信息
        var activeRow = wgWorkflow.DisplayLayout.ActiveRow;

        if (activeRow == null) {
          return new ResultModel(false, "请选择工艺");
        }
        var worklfowId = activeRow.Cells.FromKey("WorkflowID").Text;
        DataTable dt = workflowBal.GetWorkflowStepInfoByWorkflowId(worklfowId);

        //激活工艺,全部都有工时情况下
        if (dt.Select("SynergicName='否' and (unitworktime is null or setupworktime is null)").Length > 0)
        {
            return new ResultModel(false, "未全部维护工时，无法提交");
        }

        OracleHelper.ExecuteDataByEntity(new ExcuteEntity("workflow", ExcuteType.update)
        {
            ExcuteFileds = new List<FieldEntity> {new FieldEntity("status","1",FieldType.Numer)
            },
            WhereFileds = new List<FieldEntity> { new FieldEntity("workflowid", worklfowId, FieldType.Str) }
        });
        re.Message = "提交成功";

        re.IsSuccess = true;

        WriteLogToAudit(worklfowId,1, "临时工艺:" + activeRow.Cells.FromKey("WorkflowName").Text + ":" + activeRow.Cells.FromKey("WorkflowRev").Text + "工时提交");

        return re;
    }

    /// <summary>
    /// 工序工时修改记录表
    /// </summary>
    /// <param name="dr"></param>
    void WriteWorkHoursRecord(DataRow dr,string tempUnitWorkTime,string tempSetupWorkTime) {

        var workflowRow = wgWorkflow.DisplayLayout.ActiveRow;
        if (workflowRow == null)
            return;

        OracleHelper.ExecuteDataByEntity(new ExcuteEntity("workhourschangerecord", ExcuteType.insert) {
            ExcuteFileds = new List<FieldEntity>() {
                new FieldEntity("operatedate",DateTime.Now,FieldType.Date),
                new FieldEntity("operateemployeeid",UserInfo["EmployeeID"],FieldType.Str),
                new FieldEntity("tempsetupworktime",tempSetupWorkTime,FieldType.Str),
                new FieldEntity("tempunitworktime",tempUnitWorkTime,FieldType.Str),
                 new FieldEntity("setupworktime",dr["EditSetupWorkTime"],FieldType.Str),
                new FieldEntity("unitworktime",dr["EditUnitWorkTime"],FieldType.Str),
                 new FieldEntity("workhourschangerecordid",Guid.NewGuid().ToString(),FieldType.Str),
                 new FieldEntity("specid",dr["specid"],FieldType.Str),
                 new FieldEntity("workflowid",workflowRow.Cells.FromKey("WorkflowID").Text,FieldType.Str),
                  new FieldEntity("productname",workflowRow.Cells.FromKey("ProductName").Text,FieldType.Str),
            }
        });
    }

    /// <summary>
    /// 写入审计日志
    /// </summary>
    /// <param name="parentID"></param>
    /// <param name="operationType"></param>
    /// <param name="desc"></param>
    void WriteLogToAudit(string parentID,int operationType,string desc) {

        MESAuditLog ml = new MESAuditLog();
        #region 日志赋值
        ml.ParentID = parentID; ml.ParentName = parentName;
        ml.CreateEmployeeID = UserInfo["EmployeeID"];
        ml.BusinessName = businessName; ml.OperationType = operationType;
        ml.Description = desc;
        commonBal.SaveMESAuditLog(ml);
        #endregion
    }
    #endregion






}